/*
 * Img Auto Size Plugin
 */
(function($){
	
	$.imgAuto = function(){
		
		var loader = {
			load : function(src, width, height){
				var th = this;
				this.maxWidth = width;
				this.maxHeight = height;
				
				var img = $(new Image());
                img.css('border','0');
                img.css('display','none');

                function xx(){
                    if(img.width()){
                        th.adjustImgSize(img, container);
						container.removeClass('mask-image');
                    }else{
                        setTimeout(xx, 100);
                    }
                }
				
				var container = $('<div>').css({
					width: width + 'px',
					height: height + 'px'
				}).addClass('mask-image').append(img);
				
				img.load(function(){
					img.removeAttr('width');
					img.removeAttr('height');
                    xx();
                });
				img.error(function(){
					$(this).attr('src', JR.url('images/nopic.png'));
				});
				
				if(src==''){
					src = JR.url('images/nopic.png');
				}
				
				img.attr('src', src);
				
				return container;
			},
			adjustImgSize:function(img, container){
                if(img.adjusted){
                    return;
                }
                img.adjusted = true;

                var oldWidth = img.width();
                var oldHeight = img.height();

                var newWidth = oldWidth, newHeight = oldHeight;

                var widthRate = this.maxWidth/oldWidth;
                var heightRate = this.maxHeight/oldHeight;

                if(widthRate < heightRate && widthRate < 1){
                    newWidth = this.maxWidth;
                    newHeight = oldHeight*widthRate;
                }else if(heightRate < 1){
                    newWidth = oldWidth*heightRate;
                    newHeight = this.maxHeight;
                }

                img.width(newWidth);
                img.height(newHeight);
                img.css('display','block');
                
                container.width(newWidth);
                container.height(newHeight);
                
                container.css('padding',(this.maxHeight - newHeight)/2+"px "+(this.maxWidth - newWidth)/2+"px");
            }
		};
		
		return {
			load: function(src, width, height){
				return loader.load(src, width, height);
			}
		};
	};
	
})(jQuery);
